import cv2
import threading
import queue

def camera_thread(frame_queue, command_queue, stop_event):
    cap = cv2.VideoCapture(0)
    if not cap.isOpened():
        print("Error: Could not open camera.")
        return
    
    current_command = None  # 记录当前的绘制命令
    current_coords = None  # 记录当前的绘制坐标
    
    while not stop_event.is_set():
        ret, frame = cap.read()
        if not ret:
            continue
        
        # 处理命令
        if not command_queue.empty():
            current_command, current_coords = command_queue.get()  # 更新当前命令和坐标
        
        if current_command in ('red', 'green', 'blue') and current_coords:
            color_map = {'red': (0, 0, 255), 'green': (0, 255, 0), 'blue': (255, 0, 0)}
            top_left, bottom_right = current_coords
            cv2.rectangle(frame, top_left, bottom_right, color_map[current_command], 2)
        
        # 将最新的帧放入队列
        if frame_queue.qsize() < 1:  # 限制队列大小
            frame_queue.put(frame)
        
        cv2.imshow("Camera", frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    cap.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    frame_queue = queue.Queue()
    command_queue = queue.Queue()
    stop_event = threading.Event()
    
    thread = threading.Thread(target=camera_thread, args=(frame_queue, command_queue, stop_event))
    thread.start()
    
    while True:
        user_input = input("Enter command (red, green, blue, or 'capture' to save, 'exit' to quit): ")
        
        if user_input == 'exit':
            stop_event.set()
            break
        elif user_input == 'capture':
            if not frame_queue.empty():
                frame = frame_queue.get()
                filename = "captured_image.jpg"
                cv2.imwrite(filename, frame)
                print(f"Image saved as {filename}")
        elif user_input in ('red', 'green', 'blue'):
            try:
                x1, y1 = map(int, input("Enter top-left coordinates (x1 y1): ").split())
                x2, y2 = map(int, input("Enter bottom-right coordinates (x2 y2): ").split())
                command_queue.put((user_input, ((x1, y1), (x2, y2))))
            except ValueError:
                print("Invalid coordinates. Please enter integers.")
        else:
            command_queue.put((None, None))  # 其他输入清除绘图
    
    thread.join()
